package com.uenpay.oem.ui.user.login;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.qiyunxin.android.http.utils.Utils;
import com.socks.library.KLog;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.R2;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.ui.old.activity.PushServiceConn;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.login.RegisterActivity;
import com.uenpay.im.utilities.ShareUtil;
import com.uenpay.im.utilities.Toasts;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.im.weight.UenEditTextView;
import com.uenpay.im.weight.dialog.LoadDialog;
import com.uenpay.oem.ui.main.MainActivity;
import com.uenpay.oem.ui.register.ReglsterActivitycopy;
import com.uenpay.oem.util.input.InputUtils;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.common.DensityUtils;
import com.uenpay.util.common.EditFormatUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.text.InputType.TYPE_CLASS_TEXT;
import static android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD;
import static android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;

/**
 * Created by liulou on 2017/5/9. desc:
 */
@Route(path = "/main/login")
public class LoginActivity extends BaseActivity implements LoginContract.View {

	@BindView(R.id.iv_logo)
	ImageView ivLogo;
	@BindView(R.id.uen_username_layout)
	UenEditTextView uenUsername;
	@BindView(R.id.uen_pwd_layout)
	UenEditTextView uenPwd;
	@BindView(R.id.et_username)
	EditText etUserName;
	@BindView(R.id.et_pwd)
	EditText etPwd;
	@BindView(R.id.btn_login)
	Button btnLogin;
	@BindView(R.id.tv_register)
	TextView tvRegister;
	@BindView(R.id.tv_forget_pwd)
	TextView tvForgetPwd;
	@BindView(R.id.tv_customer_service)
	TextView tvCustomerService;
	@BindView(R.id.iv_sun_shine)
	ImageView ivSunShine;
	@BindView(R.id.rl_root)
	RelativeLayout rlRoot;

	private Activity mContext;
	LoginContract.Present mPresenter;

	private boolean isShowPwd;
	private Animation rotate;
	private int mainInvisibleHeight;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isFullScreen = true;
		isHideStatuBar = true;
		super.onCreate(savedInstanceState);
		setSwipeBackEnable(false);
		rotate = new RotateAnimation(0, 15, 0, 0);
		rotate.setDuration(5000);
		rotate.setRepeatCount(Animation.INFINITE);
		rotate.setRepeatMode(Animation.REVERSE);
		ivSunShine.setAnimation(rotate);
		EditFormatUtils.phoneNumAddSpace(etUserName);
		IMApplication.setFirstTime();
		btnLogin.setEnabled(false);
	}

	@Override
	public View bindView() {
		return null;
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_im_login;
	}

	@Override
	public void initView(View view) {
		initView();
		initListener();
		setPresenter(null);
		String phoneNum = IMApplication.getUserMobilePhone();
		if (!TextUtils.isEmpty(phoneNum)) {
			StringBuffer phoneFormat = new StringBuffer(phoneNum);
			phoneFormat.insert(7, ' ');
			phoneFormat.insert(3, ' ');
			etUserName.setText(phoneFormat.toString() + "");
			etUserName.setSelection(phoneNum.length());
		}
	}

	protected void initView() {
		mContext = this;
		uenUsername.setIconLeftBitmaps(R.drawable.ic_phone);
		uenUsername.setIconRightBitmaps(R.drawable.ic_clear);
		uenPwd.setIconLeftBitmaps(R.drawable.ic_pwd);
		uenPwd.setIconRightBitmaps(R.drawable.ic_eye_open);
		btnLogin.setBackgroundResource(R.drawable.shape_round_button_grey_bg);
	}

	protected void initListener() {
		uenUsername.setRightIconListener(new UenEditTextView.RightIconListener() {
			@Override
			public void onClick() {
				etUserName.setText("");
			}
		});
		uenPwd.setRightIconListener(new UenEditTextView.RightIconListener() {
			@Override
			public void onClick() {
				if (isShowPwd)
				{
					etPwd.setInputType(TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PASSWORD);
					isShowPwd = false;
					uenPwd.setIconRightBitmaps(R.drawable.ic_eye_open);
				} else {
					etPwd.setInputType(TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
					isShowPwd = true;
					uenPwd.setIconRightBitmaps(R.drawable.ic_eye_close);
				}
				etPwd.requestFocus();
			}
		});

		etPwd.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() >= 6) {
					btnLogin.setBackgroundResource(R.drawable.shape_round_button_black_bg);
					btnLogin.setEnabled(true);
				} else {
					btnLogin.setEnabled(false);
					btnLogin.setBackgroundResource(R.drawable.shape_round_button_grey_bg);
				}
			}
		});

		rlRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				Rect rect = new Rect();
				rlRoot.getWindowVisibleDisplayFrame(rect);
				mainInvisibleHeight = rlRoot.getRootView().getHeight() - rect.bottom;
				KLog.e("height" + mainInvisibleHeight);
				if (mainInvisibleHeight > 300) {// 排除虚拟按键的高度
					/*
					 * int[] location = new int[2];
					 * btnLogin.getLocationInWindow(location); int srollHeight =
					 * (location[1] + btnLogin.getHeight()) - rect.bottom;
					 */
					rlRoot.scrollTo(0, DensityUtils.dip2px(80));
				} else {
					rlRoot.scrollTo(0, 0);
				}
				btnLogin.isShown();
			}
		});

		rlRoot.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mainInvisibleHeight > 300) {
					InputUtils.switchBoard(LoginActivity.this);
				}
			}
		});
	}

	@OnClick(R2.id.btn_login)
	public void login(View view) {
		mPresenter.login(etUserName.getText().toString().trim().replace(" ", ""), etPwd.getText().toString());
	}

	@OnClick(R2.id.tv_register)
	public void register(View view) {
		ActivityHandle.startActivity(mContext, ReglsterActivitycopy.class, null, -1);
	}

	@OnClick(R2.id.tv_forget_pwd)
	public void forgetPwd(View view) {
		showForgetPwdDialog();
	}

	@OnClick(R2.id.tv_customer_service)
	public void customerService(View view) {
		String phoneNum = getResources().getString(R.string.phone); // 拨打号码
		ShareUtil.callPhone(mContext, phoneNum);
	}

	@Override
	public void setPresenter(Object presenter) {
		mPresenter = new LoginPresenter(this);
	}

	@Override
	public void showToast(String msg) {
		Toasts.shortToast(mContext, msg);
	}

	@Override
	public void dismissLoading() {
		LoadDialog.dismiss(this);
	}

	@Override
	public void showLoading() {
		LoadDialog.show(this);
	}

	@Override
	public void startLogin() {
		showLoading();
		btnLogin.setEnabled(false);
		Utils.hideSoftKeyboard(etPwd);
	}

	@Override
	public void completeLogin(int state) {
		dismissLoading();
		btnLogin.setEnabled(true);
		if (state == LoginPresenter.STATE_LOGIN_SUCCESS) {
			startChat();
		} else if (state == LoginPresenter.STATE_LOGIN_FAIL) {
			showPwdErrorDialog();
		}
	}

	private void startChat() {
		PushServiceConn.getInstance(mContext).startConn();
		Intent intent = new Intent(mContext, MainActivity.class);
		startActivity(intent);
		finish();
	}

	private void showPwdErrorDialog() {
		MyDialog.Builder alertDialog = new MyDialog.Builder(mContext);
		alertDialog.setMessage(getResources().getString(R.string.pwd_error));
		alertDialog.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		alertDialog.setNegativeButton(getResources().getString(R.string.forget_pwd), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showForgetPwdDialog();
			}
		});
		alertDialog.create().show();
	}

	private void showForgetPwdDialog() {
		BottomDialog.showBottomDialog(mContext, getResources().getString(R.string.found_pwd_by_phone), null,
				getResources().getString(R.string.cancel), getResources().getColor(R.color.the_main_color_selected),
				new IOnBottomDialogListener() {
					@Override
					public void onClicked() {
						Bundle bundle = new Bundle();
						bundle.putBoolean("is_register", false);
						ActivityHandle.startActivity(mContext, RegisterActivity.class, bundle, -1);
					}
				}, null);
	}

	public static void launch(Activity activity) {
		ARouter.getInstance().build("/main/login").navigation(activity);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		rotate.cancel();
	}
}
